<template>
  <div class="create-activity">
    <!-- 标题 -->
    <h2 class="page-title">新建活动</h2>

    <!-- 表单容器 -->
    <el-card class="form-card">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading">
        <el-skeleton loading title paragraph="4" />
      </div>

      <!-- 表单主体（仅在数据准备好后渲染） -->
      <el-form v-else :model="form" label-width="120px" :rules="rules" ref="formRef">
        <!-- 基本信息 -->
        <div class="form-section">
          <h3 class="section-title">基本信息</h3>
          <el-form-item label="活动名称" prop="name">
            <el-input
                v-model="form.name"
                placeholder="请输入活动名称"
                max-length="30"
                show-word-limit
            />
          </el-form-item>
          <el-form-item label="活动图片" prop="image">
            <el-upload
                class="upload-demo"
                :action="uploadAction"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="handleUploadSuccess"
                :file-list="fileList"
                :limit="1"
                accept="image/*"
                :auto-upload="true"
            >
              <el-button type="primary">
                <i class="el-icon-upload"></i> 上传图片
              </el-button>
            </el-upload>
            <el-image v-if="form.image" :src="form.image" class="preview-image" />
          </el-form-item>
          <el-form-item label="活动时间" prop="time">
            <el-date-picker
                v-model="form.time"
                type="daterange"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="活动说明" prop="desc">
            <el-input
                type="textarea"
                v-model="form.desc"
                placeholder="请输入活动说明"
                :rows="4"
            />
          </el-form-item>
        </div>
        <!-- 场景设计 -->
        <div class="form-section">
          <h3 class="section-title">场景设计</h3>
          <el-form-item label="活动目标" prop="target">
            <el-input v-model="form.target" placeholder="请输入活动目标" />
          </el-form-item>
<!--          <el-form-item label="适用店铺" prop="store">
            <el-button type="primary" @click="openStoreSelector">指定店铺</el-button>
          </el-form-item>-->
<!--          <el-form-item label="活动人群" prop="crowd">
            <el-button type="primary" @click="openCrowdSelector">指定人群</el-button>
          </el-form-item>-->
          <el-form-item label="自动化营销">
            <el-switch v-model="form.autoMarketing" />
          </el-form-item>
          <el-form-item label="投放渠道">
            <el-checkbox-group v-model="form.channels">
              <el-checkbox label="内容页面">内容页面</el-checkbox>
              <el-checkbox label="定时推送">定时推送</el-checkbox>
              <el-checkbox label="即时推送">即时推送</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </div>

        <!-- 奖励设置 -->
        <div class="form-section">
          <h3 class="section-title">奖励设置</h3>
          <el-form-item label="奖励类型" prop="rewardType">
            <el-radio-group v-model="form.rewardType">
              <el-radio label="优惠券">优惠券</el-radio>
              <el-radio label="积分">积分</el-radio>
              <el-radio label="商品">商品</el-radio>
            </el-radio-group>
          </el-form-item>
<!--          <el-form-item label="活动奖励" prop="reward">
            <el-button type="primary" @click="openRewardSelector">活动奖励</el-button>
          </el-form-item>-->
        </div>

        <!-- 分享设置 -->
        <div class="form-section">
          <h3 class="section-title">分享设置</h3>
          <el-form-item label="文章摘要" prop="summary">
            <el-input
                type="textarea"
                v-model="form.summary"
                placeholder="请输入文章摘要"
                :rows="4"
            />
          </el-form-item>
          <el-form-item label="短链接预览" prop="link">
            <el-input v-model="form.link" placeholder="http://" />
          </el-form-item>
        </div>
      </el-form>

      <!-- 操作按钮 -->
      <div class="form-actions">
        <el-button @click="cancel">取消</el-button>
<!--        <el-button type="primary" @click="save">保存</el-button>-->
        <el-button type="primary" @click="publish">发布</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import {
  ElMessage,
  ElMessageBox,
  ElSkeleton,
  ElImage
} from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'

// 配置API基础路径（根据后端实际地址调整）
const API_BASE = '/vv1'

const router = useRouter()
const route = useRoute()

// 表单数据
const formRef = ref(null)
const form = reactive({
  name: '',
  image: '',        // 图片URL或ID
  time: [],         // 日期范围
  desc: '',
  target: '',
  store: '',        // 店铺ID（逗号分隔）
  crowd: '',        // 人群ID（逗号分隔）
  autoMarketing: false,
  channels: [],
  rewardType: '优惠券',
  reward: '',       // 奖励ID
  summary: '',
  link: ''
})

// 上传相关
const fileList = ref([])
const uploadAction = ref(`${API_BASE}/upload`) // 图片上传API

// 组件状态
const loading = ref(true)

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入活动名称', trigger: 'blur' },
    { max: 30, message: '活动名称不能超过30个字符', trigger: 'blur' }
  ],
  image: [
    { required: true, message: '请上传活动图片', trigger: 'change' }
  ],
  time: [
    { required: true, message: '请选择活动时间', trigger: 'change' }
  ],
  desc: [
    { required: true, message: '请输入活动说明', trigger: 'blur' }
  ],
  target: [
    { required: true, message: '请输入活动目标', trigger: 'blur' }
  ],
  store: [
    { required: true, message: '请指定适用店铺', trigger: 'change' }
  ],
  crowd: [
    { required: true, message: '请指定活动人群', trigger: 'change' }
  ],
  channels: [
    { type: 'array', required: true, message: '请至少选择一个投放渠道', trigger: 'change' }
  ],
  rewardType: [
    { required: true, message: '请选择奖励类型', trigger: 'change' }
  ],
  reward: [
    { required: true, message: '请设置活动奖励', trigger: 'change' }
  ],
  summary: [
    { required: true, message: '请输入文章摘要', trigger: 'blur' }
  ],
  link: [
    { required: true, message: '请输入短链接', trigger: 'blur' },
    { pattern: /^https?:\/\/.*$/, message: '请输入有效的URL', trigger: 'blur' }
  ]
}

// 初始化
onMounted(() => {
  nextTick(() => {
    loading.value = false
    console.log('组件初始化完成，表单状态:', form)
  })
})

// 图片上传成功处理
const handleUploadSuccess = (response, file) => {
  if (response.data.code === 200) {
    form.image = response.data.url // 假设后端返回图片URL
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error('图片上传失败')
  }
}

// 预览图片
const handlePreview = (file) => {
  ElMessage.info(`预览文件：${file.name}`)
}

// 移除图片
const handleRemove = (file) => {
  form.image = ''
  fileList.value = []
  ElMessage.info(`移除文件：${file.name}`)
}

/*// 选择器弹窗（需对接实际选择逻辑）
const openStoreSelector = () => {
  ElMessageBox.alert('打开店铺选择器', '提示', {
    confirmButtonText: '关闭',
    type: 'info'
  }).then(() => {
    // 模拟选择店铺后赋值（实际需对接弹窗选择逻辑）
    form.store = '1,2,3'
  })
}*/
/*
const openCrowdSelector = () => {
  ElMessageBox.alert('打开人群选择器', '提示', {
    confirmButtonText: '关闭',
    type: 'info'
  }).then(() => {
    // 模拟选择人群后赋值（实际需对接弹窗选择逻辑）
    form.crowd = '101,102'
  })
}*/

const openRewardSelector = () => {
  ElMessageBox.alert('打开奖励选择器', '提示', {
    confirmButtonText: '关闭',
    type: 'info'
  }).then(() => {
    // 模拟选择奖励后赋值（实际需对接弹窗选择逻辑）
    form.reward = '55'
  })
}

// 取消操作
const cancel = () => {
  ElMessageBox.confirm(
      '确定取消创建活动吗？未保存的内容将丢失。',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    router.go(-1)
  }).catch(() => {
    // 取消操作
  })
}
/*

// 保存草稿
const save = async () => {
  try {
    loading.value = true
    await formRef.value.validate()

    // 构造请求参数（严格映射到后端ActivityAddParam）
    const requestData = {
      activityName: form.name,
      startDate: form.time[0],
      endDate: form.time[1],
      describes: form.desc,
      imgIds: form.image,         // 图片ID或URL
      shopIds: form.store,        // 店铺ID逗号分隔
      targetCustomer: form.crowd, // 人群ID逗号分隔
      activityTarget: form.target,
      deliveryChannel: form.channels.join(','),
      rewardType: form.rewardType === '优惠券' ? 1 :
          form.rewardType === '积分' ? 2 : 3,
      rewardCouponId: form.reward,
      shareProfile: form.summary,
      shareUrl: form.link,
      enableStatus: 0, // 0=草稿状态
      activityType: 1,  // 默认活动类型（根据业务调整）
      channelType: 1    // 默认投放渠道类型（根据业务调整）
    }

    // 调用后端API
    // const response = await axios.post(`${API_BASE}/activity/add`, requestData)
    const response = await axios.post(`http://localhost:8087/vv1/activity/add`, requestData)
    if (response.data.code === 200) {
      ElMessage.success('活动草稿已保存')
    } else {
      ElMessage.error(`保存失败：${response.data.message || '请重试'}`)
    }
  } catch (error) {
    console.error('保存活动失败:', error)
    ElMessage.error('保存活动失败，请重试')
  } finally {
    loading.value = false
  }
}
*/

// 发布活动
const publish = async () => {
  try {
    loading.value = true
    await formRef.value.validate()

    // 确认发布
    await ElMessageBox.confirm(
        '确定发布此活动吗？发布后将无法修改。',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    // 构造请求参数（发布状态）
    const requestData = {
      activityName: form.name,
      startDate: form.time[0],
      endDate: form.time[1],
      describes: form.desc,
      imgIds: form.image,
      shopIds: form.store,
      targetCustomer: form.crowd,
      activityTarget: form.target,
      deliveryChannel: form.channels.join(','),
      rewardType: form.rewardType === '优惠券' ? 1 :
          form.rewardType === '积分' ? 2 : 3,
      rewardCouponId: form.reward,
      shareProfile: form.summary,
      shareUrl: form.link,
      enableStatus: 1, // 1=发布状态
      activityType: 1,
      channelType: 1
    }

    // 调用后端API
    const response = await axios.post(`http://localhost:8087/vv1/activity/add`, requestData)
    if (response.data.code === 2000) {
      ElMessage.success('活动发布成功')
      router.push({ name: 'ActivityManagement' })
    } else {
      ElMessage.error(`发布失败：${response.data.message || '请重试'}`)
    }
  } catch (error) {
    if (error.message !== 'cancel') { // 非用户取消操作
      console.error('发布活动失败1:', error)
    }
  } finally {
    loading.value = false
  }

}
</script>

<style scoped>
.create-activity {
  padding: 20px;
  background-color: #f5f7fa;
}

.breadcrumb {
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 500;
  margin-bottom: 20px;
}

.form-card {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 20px;
  background: #fff;
}

.form-section {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.section-title {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 20px;
  color: #303133;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 30px;
}

.form-actions button {
  margin-left: 10px;
}

/* 上传组件样式 */
.upload-demo {
  display: flex;
  align-items: center;
}

.preview-image {
  width: 100px;
  height: 100px;
  margin-top: 10px;
  cursor: pointer;
}

/* 按钮悬停效果 */
button {
  transition: all 0.2s;
}

button:hover {
  transform: translateY(-1px);
}

.loading {
  text-align: center;
  padding: 40px 0;
}
</style>